﻿
using GKBErps.BLL.sys;
using GKBErps.Common;
using Microsoft.AspNetCore.Http;
  using Microsoft.AspNetCore.Mvc;
  using Microsoft.AspNetCore.Mvc.Controllers;
  using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;

namespace GKBErps.Web.Filters
{
    public class SignFilter: ActionFilterAttribute
    {

        #region 执行action前执行这个方法 
        /// <summary>
        /// 执行action前执行这个方法
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            // 判断是否检查登陆
            var noNeedCheck = false;
            if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
            {
                noNeedCheck = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
                  .Any(a => a.GetType().Equals(typeof(NoSignAttribute)));
            }
            if (noNeedCheck) return;

            // 检查登陆 - 在SignIn中判断用户合法性，将登陆信息保存在Session中，在SignOut中移除登陆信息
            // 获取登陆信息 - 这里采用Session来保存登陆信息 -- Constants是字符串常量池
            var userid = context.HttpContext.Session.GetString(SessionKey.USERID.ToString());
            var signname = context.HttpContext.Session.GetString(SessionKey.USERNAME.ToString());

            // 检查登陆信息
            if (userid == null && signname == null)
            {
                // 用户未登陆 - 跳转到登陆界面
                context.Result = new RedirectResult("/Login/Index");
            }
            base.OnActionExecuting(context);
        }
        #endregion
    }
     /// <summary>
     /// 不需要登陆的地方加个特性
     /// </summary>
     public class NoSignAttribute : ActionFilterAttribute { }
    /// <summary>
    /// 处理错误信息
    /// </summary>
    public class ErrorHandleAttribute : ExceptionFilterAttribute
    {
        sys_logBll logBll = new sys_logBll();
        public override void OnException(ExceptionContext filterContext)
        {
            //获取异常信息，入库保存
            var exception = filterContext.Exception;
            var controllerName = filterContext.RouteData.Values["controller"].ToString();
            var actionName = filterContext.RouteData.Values["action"].ToString();
            var msg = $"出错位置:{controllerName}/{actionName}----出错时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss:fff}";
            filterContext.Result = new RedirectResult("/Home/Error");
            logBll.InsertLog("ERP", "error", msg, 0, "", "", "", "error",exception.ToString());
            base.OnException(filterContext);
        }
    }
}
